<template>
  <view class="ty-city">
    <picker
			mode="multiSelector"
			@columnchange="onColumnchange"
			@change="onChange"
			:value="inputSelected"
			:range="dataTree"
			range-key="name">
    	<view class="ty-city-box">
				<view class="ty-city-text" v-if="name">{{name}}</view>
				<view class="ty-city-placeholder" v-else>{{placeholder}}</view>
			</view>
    </picker>
		<uni-icons
			v-if="name"
			size="24"
			class="ty-city-clear"
			type="clear"
			color="#c0c4cc"
			@click="onClear"></uni-icons>
  </view>
</template>

<script>
	import { allProvince, getCity, getArea } from "@/api/erp_api/region"
  /**
   * DataPicker 级联选择
   * @description 支持单列、和多列级联选择。列数没有限制，如果屏幕显示不全，顶部tab区域会左右滚动。
   * @tutorial https://ext.dcloud.net.cn/plugin?id=3796
   * @property {String} popup-title 弹出窗口标题
   * @property {Array} localdata 本地数据，参考
   * @property {Boolean} border = [true|false] 是否有边框
   * @property {Boolean} readonly = [true|false] 是否仅读
   * @property {Boolean} preload = [true|false] 是否预加载数据
   * @value true 开启预加载数据，点击弹出窗口后显示已加载数据
   * @value false 关闭预加载数据，点击弹出窗口后开始加载数据
   * @property {Boolean} step-searh = [true|false] 是否分布查询
   * @value true 启用分布查询，仅查询当前选中节点
   * @value false 关闭分布查询，一次查询出所有数据
   * @property {String|DBFieldString} self-field 分布查询当前字段名称
   * @property {String|DBFieldString} parent-field 分布查询父字段名称
   * @property {String|DBCollectionString} collection 表名
   * @property {String|DBFieldString} field 查询字段，多个字段用 `,` 分割
   * @property {String} orderby 排序字段及正序倒叙设置
   * @property {String|JQLString} where 查询条件
   * @event {Function} popupshow 弹出的选择窗口打开时触发此事件
   * @event {Function} popuphide 弹出的选择窗口关闭时触发此事件
   */
  export default {
    name: 'TyDataPicker',
    emits: ['change', 'update:modelValue'],
    props: {
      placeholder: {
        type: String,
        default: '请选择'
      },
			modelValue: {
				type: String,
				default: ''
			},
			value: {
				type: String,
				default: ''
			}
    },
    data() {
      return {
        isOpened: false,
				dataTree: [
					[],
					[],
					[]
				],
				name: '',
        inputSelected: [0 , 0, 0],
				addr: [],
				provinceList: []
      }
    },
    created() {
      this.$nextTick(() => {
        this.load();
      })
    },
    watch: {
			value: {
				handler(newVal, oldVal) {
					if (newVal === null) {
						this.name = ''
						return
					}
					this.name = newVal
					this.setCity()
				}
			},
			modelValue: {
				handler(newVal, oldVal) {
					if (newVal === null) {
						this.name = ''
						return
					}
					this.name = newVal
					this.setCity()
				}
			},
			provinceList: {
				handler(newVal) {
					console.log(newVal)
					if (this.name) {
						this.setCity()
					}
				}
			}
    },
    methods: {
      load() {
        this.getAllProvince()
      },
			onClear() {
				this.name = ''
				this.$emit('change')
			},
      onChange(e) {
				const province = this.dataTree[0][this.inputSelected[0]] ? this.dataTree[0][this.inputSelected[0]] : null
				const city = this.dataTree[1][this.inputSelected[1]] ? this.dataTree[1][this.inputSelected[1]] : null
				const area = this.dataTree[2][this.inputSelected[2]] ? this.dataTree[2][this.inputSelected[2]] : null
        const name = `${province?.name ? province?.name : ''}${city?.name ? city?.name : ''}${area?.name ? area?.name : ''}`
				this.name = name
				this.$emit('update:modelValue', name)
				this.$emit('change', {
					provinceCode: province?.code,
					cityCode: city?.code,
					areaCode: area?.code,
					provinceName: province?.name,
					cityName: city?.name,
					areaName: area?.name,
					name: this.name
				})
      },
			onColumnchange(e) {
				this.inputSelected[e.detail.column] = e.detail.value
				switch (e.detail.column) {
					case 0: //拖动第1列
						const code1 = this.dataTree[e.detail.column][e.detail.value]?.code
						if (code1) {
							this.getCityData(code1)
							this.inputSelected.splice(1, 1, 0)
							this.inputSelected.splice(2, 1, 0)
						}
						break
					case 1: //拖动第2列
						const code2 = this.dataTree[e.detail.column][e.detail.value]?.code
						if (code2) {
							this.getAreaData(code2)
							this.inputSelected.splice(2, 1, 0)
						}
						break
				}
				this.$forceUpdate()
			},
			// 获取省
			getAllProvince() {
				allProvince().then(res => {
					const province = res.data.map((item, index) => {
						return {
							...item,
							value: item.code,
							text: item.name,
							level: 1,
							index,
							parentCode: 0
						}
					}) || []
					this.provinceList = province
					this.dataTree[0] = province
				})
			},
			// 获取市
			getCityData(code, type) {
				getCity({
					code
				}).then(res => {
					const city = res.data.map((item, index) => {
						if (type === 'default' && this.modelValue.indexOf(item.name) > -1) {
							this.getAreaData(item.code, 'default')
							this.inputSelected.splice(1, 1, index)
						}
						return {
							...item,
							value: item.code,
							text: item.name,
							level: 2,
							index,
							parentCode: code
						}
					}) || []
					this.dataTree[1] = city
					if (!type) {
						this.getAreaData(city[0].code)
					}
				})
			},
			// 获取区
			getAreaData(code, type) {
				getArea({
					code
				}).then(res => {
					const area = res.data.map((item, index) => {
						if (type === 'default' && this.modelValue.indexOf(item.name) > -1) {
							this.inputSelected.splice(2, 1, index)
						}
						return {
							...item,
							index,
							value: item.code,
							text: item.name,
							level: 3,
							parentCode: code
						}
					}) || []
					this.dataTree[2] = area
				})
			},
			setCity() {
				const province = this.dataTree[0].filter(item => this.modelValue.indexOf(item.name) > -1)
				if (province.length > 0) {
					this.inputSelected.splice(0, 1, province[0].index)
					this.getCityData(province[0].code, 'default')
				} else if (this.dataTree[0].length > 0) {
					this.getCityData(this.dataTree[0][0].code)
				}
			}
    }
  }
</script>

<style lang="scss">
  .ty-city {
		position: relative;
		&-box {
			display: flex;
			box-sizing: border-box;
			flex-direction: row;
			align-items: center;
			border: 1px solid #dcdfe6;
			border-radius: 4px;
			overflow: hidden;
			font-size: 12px;
			height: 35px;
			padding-left: 10px;
		}
		&-placeholder {
			color: #999;
		}
		&-clear {
			position: absolute;
			top: 50%;
			right: 0px;
			margin: 0 5px;
			margin-top: -12px;
		}
	}
</style>
